package com.itboye.mengwu.testpic.ui;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseActivity;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.ImageCompressAndUpload;
import com.itboye.core.utils.ImageCompressAndUpload.OnUploadlistener;
import com.itboye.core.utils.SPUtils;
import com.itboye.core.utils.SoftwareUtil;
import com.itboye.core.utils.XImageLoader;
import com.itboye.mengwu.R;
import com.itboye.mengwu.app.MainApplication;
import com.itboye.mengwu.app.ui.aiwujia.ActivityAiwujiaMomPublish.GridAdapter;
import com.itboye.mengwu.data.model.LuntanTieZiBean;
import com.itboye.mengwu.data.presenter.TieZiPresenter;
import com.itboye.mengwu.widget.PhotoSelectFragment;
import com.itboye.mengwu.widget.PhotoSelectFragment.PhotoSelectListener;

public class PublishedActivity extends BaseActivity implements Observer {
	public final int EXTERNAL_CAMERA_REQ_CODE = 11;
	public final int EXTERNAL_STORE_REQ_CODE = 12;
	private GridView noScrollgridview;
	private ImageBucketAdapter adapter;
	private TextView activity_selectimg_send;
	private ImageView imgPublishBack;
	// 标题
	// private EditText editextTitle;
	// 内容
	private EditText editexContext;
	// private String title;
	private String contextEd;
	private String type;
	// ImageView img;
	LinearLayout faceInputContainer;
	public static ArrayList<String> imgUrls = new ArrayList<>();
	String fid = "4";

	@Override
	public int initView() {
		// TODO Auto-generated method stub

		return R.layout.activity_selectimg;
	}

	@Override
	public void onMyCreate() {
		// TODO Auto-generated method stub

		Init();
		imgPublishBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				// showAlertDialog();
				editexContext.setText("");
				attachments = new StringBuffer();
				Bimp.bmp.clear();
				imgUrls.clear();
				adapter.notifyDataSetChanged();
				finish();
			}
		});
	}

	/** 监听对话框里面的button点击事件 */
	DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序
				finish();
				break;
			// case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框
			// break;
			default:
				break;
			}
		}
	};
	private StringBuffer attachments;
	protected ArrayList<String> uploadedUrl = new ArrayList<String>();
	protected PopupWindows popupWindow;

	public void Init() {
		type = getIntent().getStringExtra("type");

		adapter = new ImageBucketAdapter(PublishedActivity.this, imgUrls);
		noScrollgridview.setAdapter(adapter);
		noScrollgridview.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (arg2 == imgUrls.size()) {
					SoftwareUtil.showOrHideSoftware(arg1, MainApplication.context, false);
					popupWindow = new PopupWindows(PublishedActivity.this,
							noScrollgridview);
				} else {
					Intent intent = new Intent(PublishedActivity.this,
							PhotoActivity.class);
					intent.putExtra("imgUrls", imgUrls);
					intent.putExtra("ID", arg2);
					intent.putExtra("type", "myDongTai");
					startActivity(intent);
				}
			}
		});
		activity_selectimg_send = (TextView) findViewById(R.id.activity_selectimg_send);
		activity_selectimg_send.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				onBitMap();
			}

		});
	}

	public void onBitMap() {
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < imgUrls.size(); i++) {
			String Str = imgUrls.get(i).substring(
					imgUrls.get(i).lastIndexOf("/") + 1,
					imgUrls.get(i).lastIndexOf("."));
			list.add(FileUtils.SDPATH + Str + ".JPEG");
		}

		// 高清的压缩图片全部就在 list 路径里面了
		// 高清的压缩过的 bmp 对象 都在 Bimp.bmp里面
		// 完成上传服务器后 .........

		// title = editextTitle.getText().toString().trim();
		contextEd = editexContext.getText().toString().trim();

		// if (title == null || title == "") {
		// ByAlert.alert("请输入标题");
		// return;
		// }
		if (contextEd == null || contextEd == "" || contextEd.length() == 0) {
			ByAlert.alert("请输入内容");
			return;
		}
		if (imgUrls.size() <= 0) {
			ByAlert.alert("请选择照片");
			return;
		}
		showProgressDialog("正在发布中，请稍后", true);
		final TieZiPresenter tanPresenter = new TieZiPresenter(this);
		if (imgUrls.size() > 0) {
			for (int j = 0; j < imgUrls.size(); j++) {
				if (j <= 9) {
					System.out.println("路径" + imgUrls.get(j));
					ImageCompressAndUpload.getInstance().execute(
							imgUrls.get(j), new OnUploadlistener() {

								@Override
								public void OnSuccess(String resultData) {
									uploadedUrl.add(resultData);
									System.out.println("rse" + resultData);
									if (uploadedUrl.size() == imgUrls.size()) {
										if (uploadedUrl.size() > 0) {

											attachments = new StringBuffer();
											attachments.append(uploadedUrl
													.get(0));
											for (int i = 1; i < uploadedUrl
													.size(); i++) {
												attachments.append(",").append(
														uploadedUrl.get(i));
											}

										}
										LuntanTieZiBean bean = new LuntanTieZiBean();
										bean.setUid((String) SPUtils.get(
												PublishedActivity.this, null,
												SpPublicParams.UID, ""));
										// bean.setSubject(title);
										bean.setMessage(contextEd);
										bean.setAuthor((String) SPUtils.get(
												PublishedActivity.this, null,
												SpPublicParams.NICK_NAME, ""));
										bean.setFid(fid);
										// bean.setTypeid(1 + "");
										bean.setAttachments(attachments);
										tanPresenter.add(bean);

										try {
											closeProgressDialog();
										} catch (Exception e) {
											// TODO: handle exception
										}
									}

								}

								@Override
								public void OnError(String resultData) {
									// if (wait != null) {
									// wait.dismiss();
									// }
									//
									ByAlert.alert("发表出错了╰(￣▽￣)╭");
									try {
										closeProgressDialog();
									} catch (Exception e) {
										// TODO: handle exception
									}
									// toast.show();
								}
							}, "bbs");
				}
			}
		} else {
			// LuntanTieZiBean bean = new LuntanTieZiBean();
			// bean.setUid((String) SPUtils.get(PublishedActivity.this, null,
			// SpPublicParams.UID, ""));
			// // bean.setSubject(title);
			// bean.setMessage(contextEd);
			// bean.setAuthor((String) SPUtils.get(PublishedActivity.this, null,
			// SpPublicParams.NICK_NAME, ""));
			// bean.setFid(fid);
			// bean.setAttachments(null);
			// tanPresenter.add(bean);
		}

		// bean.seta

		// FileUtils.deleteDir();

	}

	public class PopupWindows extends PopupWindow {

		public PopupWindows(Context mContext, View parent) {

			View view = View
					.inflate(mContext, R.layout.item_popupwindows, null);
			view.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view
					.findViewById(R.id.ll_popup);
			ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.push_bottom_in_2));

			setWidth(LayoutParams.FILL_PARENT);
			setHeight(LayoutParams.FILL_PARENT);
			setBackgroundDrawable(new BitmapDrawable());
			setFocusable(true);
			setOutsideTouchable(true);
			setContentView(view);
			showAtLocation(parent, Gravity.BOTTOM, 0, 0);
			update();

			Button bt1 = (Button) view
					.findViewById(R.id.item_popupwindows_camera);
			Button bt2 = (Button) view
					.findViewById(R.id.item_popupwindows_Photo);
			Button bt3 = (Button) view
					.findViewById(R.id.item_popupwindows_cancel);
			bt1.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {

					cameraPermission();
				}
			});
			bt2.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					// Intent intent = new Intent(PublishedActivity.this,
					// TestPicActivity.class);
					// startActivity(intent);
					// dismiss();
					// finish();
					storePermission();
					dismiss();
				}
			});
			bt3.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					dismiss();
				}
			});

		}
	}

	class PhotoSelect implements PhotoSelectListener {

		@Override
		public void onPhotoSelectFinish(List<String> paths) {
			for (String string : paths) {
				imgUrls.add(string);
			}
			adapter = new ImageBucketAdapter(PublishedActivity.this, imgUrls);
			noScrollgridview.setAdapter(adapter);
		}

	}

	private static final int TAKE_PICTURE = 0x000000;
	private String path = "";

	public void photo() {
		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		File file = new File(Environment.getExternalStorageDirectory()
				+ "/myimage/", String.valueOf(System.currentTimeMillis())
				+ ".jpg");
		path = file.getPath();
		Uri imageUri = Uri.fromFile(file);
		openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		startActivityForResult(openCameraIntent, TAKE_PICTURE);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case TAKE_PICTURE:
			if (imgUrls.size() < 9 && resultCode == -1) {
				imgUrls.add(path);
			}
			adapter = new ImageBucketAdapter(PublishedActivity.this, imgUrls);
			noScrollgridview.setAdapter(adapter);
			break;
		}
		if (requestCode == 101 && resultCode == 102) {
			adapter = new ImageBucketAdapter(PublishedActivity.this, imgUrls);
			noScrollgridview.setAdapter(adapter);
		}
	}

	/**
	 * 退出提醒
	 */
	// public void showAlertDialog() {
	//
	// CustomDialog.Builder builder = new CustomDialog.Builder(this);
	// builder.setMessage("返回后将不会保存数据的哟！");
	// builder.setTitle("萌屋提示");
	// builder.setPositiveButton("确定要退出吗",
	// new DialogInterface.OnClickListener() {
	// public void onClick(DialogInterface dialog, int which) {
	// dialog.dismiss();
	// // 设置你的操作事项
	// finish();
	//
	// }
	// });
	//
	// builder.setNegativeButton("取消",
	// new android.content.DialogInterface.OnClickListener() {
	// public void onClick(DialogInterface dialog, int which) {
	// dialog.dismiss();
	// }
	// });
	//
	// builder.create().show();
	//
	// }

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		// ByAlert.alert("" + entity.getData());
		editexContext.setText("");
		attachments = new StringBuffer();
		Bimp.bmp.clear();
		imgUrls.clear();
		adapter.notifyDataSetChanged();
		try {
			closeProgressDialog();
		} catch (Exception e) {
			// TODO: handle exception
		}
		setResult(102);
		ByAlert.alert("发布成功");
		finish();
	}

	public void cameraPermission() {
		if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

			// 如果App的权限申请曾经被用户拒绝过，就需要在这里跟用户做出解释
			if (ActivityCompat.shouldShowRequestPermissionRationale(this,
					Manifest.permission.CAMERA)) {
				Toast.makeText(this, "请去设置给小萌添加个权限，否则打不开相机。",
						Toast.LENGTH_SHORT).show();
			} else {
				// 进行权限请求
				ActivityCompat.requestPermissions(this,
						new String[] { Manifest.permission.CAMERA },
						EXTERNAL_CAMERA_REQ_CODE);
			}
		} else {
			photo();
			popupWindow.dismiss();
		}
	}

	public void storePermission() {
		if (ContextCompat.checkSelfPermission(this,
				Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

			// 如果App的权限申请曾经被用户拒绝过，就需要在这里跟用户做出解释
			if (ActivityCompat.shouldShowRequestPermissionRationale(this,
					Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
				Toast.makeText(this, "请去设置给小萌添加个权限，否则不能读取相册。",
						Toast.LENGTH_SHORT).show();
			} else {
				// 进行权限请求
				ActivityCompat.requestPermissions(this, new String[] {
						Manifest.permission.WRITE_EXTERNAL_STORAGE,
						Manifest.permission.READ_EXTERNAL_STORAGE },
						EXTERNAL_STORE_REQ_CODE);
			}
		} else {
			new PhotoSelectFragment(new PhotoSelect(), 9).show(
					getSupportFragmentManager(), null);
		}
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, String[] arg1,
			int[] grantResults) {
		// TODO Auto-generated method stub
		super.onRequestPermissionsResult(requestCode, arg1, grantResults);

		switch (requestCode) {

		case EXTERNAL_CAMERA_REQ_CODE: {
			if (grantResults == null || "".equals(grantResults)) {
				return;
			} else {
				if (grantResults.length > 0
						&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
					// 申请成功，进行相应操作
					photo();
					popupWindow.dismiss();
				} else {
					// 申请失败，可以继续向用户解释。

				}
			}
			return;
		}
		case EXTERNAL_STORE_REQ_CODE: {

			if (grantResults.length > 0
					&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
				// 申请成功，进行相应

				PhotoSelectFragment photoSelectFragment = new PhotoSelectFragment(
						new PhotoSelect(), 9);
				photoSelectFragment.show(getSupportFragmentManager(), null);

			} else {
				// 申请失败，可以继续向用户解释。

			}
			return;
		}
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle arg0) {
		// TODO Auto-generated method stub
		// super.onSaveInstanceState(arg0);
	}

}
